import base64
import pickle

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection
import json
from goods.models import SKU


# Create your views here.



class CartsView(View):
    def post(self, request):
        # 获取请求体中的数据
        data = request.body.decode()
        data_dict = json.loads(data)
        sku_id = data_dict.get('sku_id')
        count = data_dict.get('count')
        selected = True
        # 验证商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return JsonResponse({'error': '商品不存在'}, status=400)

        if int(count) > sku.stock:
            return JsonResponse({'error': '库存不足'}, status=400)

        # 判断用户是否登陆
        user = request.user

        if user.is_authenticated:
            # 登陆过则存入redis
            client = get_redis_connection('carts')
            # 需要存储用户,数量,商品,是否被选中
            client.hincrby('carts_%s' % user.id, sku_id, count)
            if selected:
                client.sadd('carts_selected_%s' % user.id, sku_id)
            return JsonResponse({'code': 0})
        else:
            # 未登录过存入cookie,以字典的形式
            cart_cookie = request.COOKIES.get('cart_cookie')
            # 判断此用户cookie中是否有购物车数据
            if cart_cookie:
                data_dict = pickle.loads(base64.b64decode(cart_cookie))
            else:
                data_dict = {}
            # 存储形式{sku_id:{count:10,selected:True}}
            sku_data = data_dict.get(sku_id)
            if sku_data:
                count += data_dict[sku_id]['count']
                selected = data_dict[sku_id]['selected']

            data_dict = {sku_id: {
                'count': count,
                'selected': selected
            }}
            # 加密
            cart_cookie = base64.b64encode(pickle.dumps(data_dict)).decode()
            response = JsonResponse({'code': 0})
            response.set_cookie('cart_cookie', cart_cookie, 60 * 60 * 2)
            return response

    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # 用户登陆过,从redis中获取数据
            client = get_redis_connection('carts')
            sku_id_count = client.hgetall('carts_%s' % user.id)
            sku_id_selected = client.smembers('carts_selected_%s' % user.id)
            data_dict = {}
            for sku_id ,count in sku_id_count.items():
                data_dict[int(sku_id)]={
                    'count':int(count),
                    'selected':sku_id in sku_id_selected
                }
        else:
            data_dict = request.COOKIES.get('cart_cookie')
            if data_dict:
                data_dict = pickle.loads(base64.b64decode(data_dict))
            else:
                data_dict ={}

        sku_keys = data_dict.keys()
        skus = SKU.objects.filter(id__in = sku_keys)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'price':str(sku.price),
                'count':data_dict[sku.id]['count'],
                'caption': sku.caption,
                'default_image_url':sku.default_image.url,
                'selected':str(data_dict[sku.id]['selected']),
            })
        return render(request,'cart.html',{'cart_skus':cart_skus})

    def put(self,request):
        data = request.body.decode()
        data_dict = json.loads(data)
        count = data_dict.get('count')
        sku_id = data_dict.get('sku_id')
        selected = data_dict.get('selected')
        # 验证商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return JsonResponse({'error': '商品不存在'}, status=400)

        if int(count) > sku.stock:
            return JsonResponse({'error': '库存不足'}, status=400)

        user = request.user
        if user.is_authenticated:
            # 登陆过对redis进行操作
            client = get_redis_connection('carts')
            client.hset('carts_%s'%user.id,sku_id,count)

            if selected:
                client.sadd('carts_selected_%s'%user.id,sku_id)
            else:
                client.srem('carts_selected_%s'%user.id,sku_id)

            cart_sku = {
                'id':sku.id,
                'name':sku.name,
                'price':str(sku.price),
                'count':count,
                'default_image_url':sku.default_image.url,
                'selected':str(selected)
            }
            return JsonResponse({'code':0,'cart_sku':cart_sku})
        else:
            # 没有登陆过对cookie操作
            cart_cookie = request.COOKIES.get('cart_cookie')
            # 判断此用户cookie中是否有购物车数据
            if cart_cookie:
                # 解密
                data_dict = pickle.loads(base64.b64decode(cart_cookie))
            else:
                data_dict = {}
            data_dict[sku_id] =  {
                'count': count,
                'selected': selected}
            cart_sku = {
                'id': sku.id,
                'name': sku.name,
                'price': str(sku.price),
                'count': count,
                'selected': str(selected),
                'default_image_url': sku.default_image.url
            }
            #加密
            cart_cookie = base64.b64encode(pickle.dumps(data_dict)).decode()
            # 将数据保存到cookie中
            response = JsonResponse({'code': 0, 'cart_sku': cart_sku})
            response.set_cookie('cart_cookie', cart_cookie, 60 * 60 * 2)
            return response

    def delete(self,request):
        data = request.body.decode()
        data_dict = json.loads(data)
        sku_id = data_dict.get('sku_id')

        try:
            sku = SKU.objects.get(id = sku_id)
        except:
            return JsonResponse({'error':'商品不存在'},status=400)

        user = request.user
        if user.is_authenticated:
            client = get_redis_connection('carts')
            client.hdel('carts_%s'%user.id,sku_id)
            client.srem('carts_selected_%s'%user.id,sku_id)
            return JsonResponse({'code':0})
        else:
            cart_cookie = request.COOKIES.get('cart_cookie')
            if cart_cookie:
                data_dict = pickle.loads(base64.b64decode(cart_cookie))
            else:
                return JsonResponse({'code':0})

            if sku_id in data_dict.keys():
                del data_dict[sku_id]

            cart_cookie = base64.b64encode(pickle.dumps(data_dict)).decode()
            response = JsonResponse({'code':0})
            response.set_cookie('cart_cookie',cart_cookie,60*60*2)
            return response


class CartsSelectView(View):
    def put(self,request):
        data = request.body.decode()
        data_dict = json.loads(data)
        selected = data_dict.get('selected')

        user = request.user
        if user.is_authenticated:
            client = get_redis_connection('carts')
            # 获取redis中用户所有商品
            sku_id_count = client.hgetall('carts_%s'%user.id)
            # 购物车中所有的商品的id值
            sku_ids = sku_id_count.keys()
            if selected:
                client.sadd('carts_selected_%s'%user.id,*sku_ids)

            else:
                client.srem('carts_selected_%s'%user.id,*sku_ids)

            return JsonResponse({'code':0})
        else:
            cart_cookie = request.COOKIES.get('cart_cookie')
            # 判断此用户cookie中是否有购物车数据
            if cart_cookie:
                # 解密
                data_dict = pickle.loads(base64.b64decode(cart_cookie))
            else:
                return JsonResponse({'code':0})

            for id, dict in data_dict.items():
                dict['selected'] = selected

            # 加密
            cart_cookie = base64.b64encode(pickle.dumps(data_dict)).decode()
            # 将数据保存到cookie中
            response = JsonResponse({'code': 0})
            response.set_cookie('cart_cookie', cart_cookie, 60 * 60 * 2)
            return response


class CartsSimpleView(View):
    def get(self,request):
        user = request.user
        if user.is_authenticated:
            # 用户登陆过,从redis中获取数据
            client = get_redis_connection('carts')
            sku_id_count = client.hgetall('carts_%s' % user.id)
            sku_id_selected = client.smembers('carts_selected_%s' % user.id)
            data_dict = {}
            for sku_id, count in sku_id_count.items():
                data_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in sku_id_selected
                }
        else:
            data_dict = request.COOKIES.get('cart_cookie')
            if data_dict:
                data_dict = pickle.loads(base64.b64decode(data_dict))
            else:
                data_dict = {}

        sku_keys = data_dict.keys()
        skus = SKU.objects.filter(id__in=sku_keys)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'price': str(sku.price),
                'count': data_dict[sku.id]['count'],
                'caption': sku.caption,
                'default_image_url': sku.default_image.url,
                'selected': str(data_dict[sku.id]['selected']),
            })
        return JsonResponse({'cart_skus': cart_skus})